package com.mall.order.biz.handler;

import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @Description: 利用mq发送延迟取消订单消息
 * @Author： ciggar
 * @Date: 2019-09-17 23:14
 **/
@Component
@Slf4j
public class SendMessageHandler extends AbstractTransHandler {

	@Autowired
	private DefaultMQProducer producer;

	@PostConstruct
	public void init() {
	    try {
	    	producer.setProducerGroup("delay_order_producer");
	        producer.start();
	    } catch (MQClientException e) {
	        e.printStackTrace();
	    }
	}

	@Override
	public boolean isAsync() {
		return false;
	}

	// todo
	@Override
	public boolean handle(TransHandlerContext context) {

		CreateOrderContext createOrderContext = (CreateOrderContext) context;

		String orderId = createOrderContext.getOrderId();
		// 准备消息
		Message message = new Message();
		message.setTopic("delay_order");
		message.setBody(orderId.getBytes(Charset.forName("utf-8")));
		// "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h"
		// 设置消息延迟级别为16，也就是延迟30m。
		message.setDelayTimeLevel(16);
		SendResult sendResult = null;
		Exception ex = null;
		try {
			sendResult = producer.send(message);
		} catch (MQClientException e) {
			e.printStackTrace();
		} catch (RemotingException e) {
			e.printStackTrace();
		} catch (MQBrokerException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
			log.info("消息发送成功： " + sendResult.getMsgId());
			return true;
		}

		log.info("消息发送失败");
        return false;
	}


}